package tasks;

import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.SwingWorker;

import tools.Format;
import core.Torrent;
import core.TorrentManager;

public class UpdateSpeed extends SwingWorker {

	@Override
	protected Object doInBackground() {		
		ArrayList<Torrent> torrents = new ArrayList<Torrent>();
		ArrayList<Torrent> oldTorrents = new ArrayList<Torrent>();
		HashMap<Torrent, ArrayList<Double>> ups = new HashMap<Torrent, ArrayList<Double>>();
		HashMap<Torrent, ArrayList<Double>> downs = new HashMap<Torrent, ArrayList<Double>>();

		double up = -1, down = -1, totalUp = 0, totalDown = 0;

		do {
			try {
				oldTorrents = new ArrayList<Torrent>(torrents);
				torrents = new ArrayList<Torrent>(TorrentManager.getInstance().getTorrents());
				
				for(int i=0; i<oldTorrents.size(); i++) {
					if(!torrents.contains(oldTorrents.get(i))) {
						ups.remove(oldTorrents.get(i));
						downs.remove(oldTorrents.get(i));
					}
				}				
				
				for(int u=0; u<torrents.size(); u++) {					
					if(!oldTorrents.contains(torrents.get(u))) {						
						ups.put(torrents.get(u), new ArrayList<Double>());
						downs.put(torrents.get(u), new ArrayList<Double>());
					}
				}
				
				totalUp = 0.0;
				totalDown = 0.0;
				
				for(int i=0; i<torrents.size(); i++) {
					if(ups.get(torrents.get(i)).size() >= 10) {
						ups.get(torrents.get(i)).remove(0);
					}
					
					if(downs.get(torrents.get(i)).size() >= 10) {
						downs.get(torrents.get(i)).remove(0);
					}
					ups.get(torrents.get(i)).add((double) torrents.get(i).getUploadSince());
					downs.get(torrents.get(i)).add((double) torrents.get(i).getDownloadSince());
					
					up = 0;
					for(int j=0; j<ups.get(torrents.get(i)).size(); j++) {
						up += ups.get(torrents.get(i)).get(j);
					}
					
					up /= (double) ups.get(torrents.get(i)).size();
					
					down = 0;
					for(int j=0; j<downs.get(torrents.get(i)).size(); j++) {
						down += downs.get(torrents.get(i)).get(j);
					}
					
					down /= (double) downs.get(torrents.get(i)).size();
					
					this.firePropertyChange("upSpeed", torrents.get(i).getName(), Format.bytes(up)+"/s");
					this.firePropertyChange("downSpeed", torrents.get(i).getName(), Format.bytes(down)+"/s");
					
					totalUp += up;
					totalDown += down;
				}
			
			this.firePropertyChange("totalUp", 0, Format.bytes(totalUp)+"/s");
			this.firePropertyChange("totalDown", 0, Format.bytes(totalDown)+"/s");

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}			
			} catch(Exception e) {
			}

		} while(true);
	}

}
